import {ethers} from "ethers";
import store from "../store";
import { usdtAbi } from "@/utils/abi/usdtAbi"
import {
  ref,
} from "vue";
import { chainId} from "@/utils/config";
import { usdtContract ,btcContract} from "./config";
let provider, signer, accounts, balance
const switchNetwork = async (chain) => {
  try {
    var gasHex = ethers.utils.hexValue(chainId)
    if (chain && (gasHex == chain)) {
      return
    }
    await window.ethereum.request({
      "method": "wallet_switchEthereumChain",
      "params": [{
        "chainId": gasHex
      }]
    });
    window.location.reload()
    return
  } catch (error) {

  }
}
const eth = {
  async getBalanceOf(contractAddress, decimals, account) {
    let value = 0;
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const Contract = new ethers.Contract(
      contractAddress,
      usdtAbi.contractAbi,
      provider
    );
    try {
      let accounts = await provider.send("eth_requestAccounts", []);
      let address = account || accounts[0];
      value = parseFloat(
        Number(
          ethers.utils.formatUnits(await Contract.balanceOf(address), decimals)
        ).toFixed(6)
      );
      return value;
    } catch (error) {
      return value;
    }
  },
  // 获取btc和usdt
 async getUsdtAndBtc() {
    let account = await this.getAccount()
    let usdt = await this.getBalanceOf(usdtContract[0],usdtContract[3],account)
    let btc = await this.getBalanceOf(btcContract[0],btcContract[3],account)
    store.commit("changeUsdtBalance",usdt)
    store.commit("changeBtcBalance",btc)
  },

  async getAllowance(contractAddress, payContract, decimals) {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const Contract = new ethers.Contract(
      contractAddress,
      usdtAbi.contractAbi,
      provider
    );
    let accounts = await provider.send("eth_requestAccounts", []);
    let address = accounts[0];
    let value = await Contract.allowance(address, payContract);
    return ethers.utils.formatUnits(value, decimals);
  },
  async approve(value, tokenContract, payContract, decimals) {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = await provider.getSigner();
    const Contract = new ethers.Contract(
      tokenContract,
      usdtAbi.contractAbi,
      provider
    );
    const ContractWithSinger = Contract.connect(signer);
    let amount = ethers.utils.parseUnits(String(value), decimals);
    let hex = await ContractWithSinger.approve(payContract, amount);
    await hex.wait();
  },
  async getAccount() {
    let address = "";
    if (store.state.address) {
      address = store.state.address;
    } else {
      provider = new ethers.providers.Web3Provider(window.ethereum);
      accounts = await provider.send("eth_requestAccounts", []);
      address = accounts[0].toLowerCase();
      store.commit("changeAddress", address);
    }
    return address;
  },
  async getTokenName() {
    let tokenName = "";
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const Contract = new ethers.Contract(
         usdtContract,
         usdtAbi.contractAbi,
         provider
       );
       tokenName = await Contract.symbol();
      store.commit("changeTokenName", tokenName);
  },
  async linkWallet() {
    try {
      provider = await new ethers.providers.Web3Provider(window.ethereum);
      let network = await provider.getNetwork();
      if (parseInt(network.chainId) != chainId) {
        switchNetwork();
        return;
      }
      signer = await provider.getSigner();
      accounts = await provider.send("eth_requestAccounts", []);
      let address = accounts[0];
      balance = await provider.getBalance(address);
      balance = parseFloat(ethers.utils.formatUnits(balance._hex, 18)).toFixed(
        4
      );
      store.commit("changeAddress", address);
      store.commit("BALANCE", balance);
    } catch (err) {
      console.log(err);
    }
  },
  async getBalance(provider, address) {
    balance = await provider.getBalance(address);
    store.commit("BALANCE", balance);
  },
};
export {
  switchNetwork,
}
// mouse.js
export default eth